package cn.edu.zafu.bigdata.x.wupeng.a;

import java.util.Random;
import java.util.Scanner;

public class guessnumber {
    private int maxAttempts;
    private int numberToGuess;
    private Scanner scanner;
    private Random random;

    public guessnumber(int maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.scanner = new Scanner(System.in);
        this.random = new Random();
    }

    private void startNewGame() {
        numberToGuess = random.nextInt(100) + 1; // 生成1到100之间的随机数
        int attempts = 0;
        int guess;

        System.out.println("欢迎来到猜数字游戏！你有" + maxAttempts + "次机会猜对数字。");

        while (attempts < maxAttempts) {
            System.out.print("请输入你猜的数字（1-100）：");
            guess = scanner.nextInt();

            if (guess == numberToGuess) {
                System.out.println("恭喜你！你猜对了数字！");
                return;
            } else if (guess < numberToGuess) {
                System.out.println("你猜的数字太小了。");
            } else {
                System.out.println("你猜的数字太大了。");
            }

            attempts++;
            System.out.println("你还有" + (maxAttempts - attempts) + "次机会。");
        }

        System.out.println("很遗憾，你没有在规定的次数内猜对数字。正确的数字是：" + numberToGuess);
    }

    private void playAgain() {
        System.out.print("你想再玩一次吗？(yes/no)：");
        String answer = scanner.next();
        if ("yes".equalsIgnoreCase(answer)) {
            startNewGame();
        } else {
            System.out.println("感谢你玩猜数字游戏，再见！");
        }
    }

    public void run() {
        startNewGame();
        playAgain();
    }

    public static void main(String[] args) {
        guessnumber game = new guessnumber(5); // 设置最大尝试次数为5
        game.run();
    }
}